import axios from 'axios'
import config from '../config/url'
import router from '../router'
import JLBlog from '../components/index'
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 6000
})

// 请求拦截
service.interceptors.request.use(config => {
  JLBlog.Loading.show()
  return config
})

// 响应拦截
service.interceptors.response.use(res => {
  JLBlog.Loading.hide()
  if (res.status === 200) {
    if (res.data.code === 401) {
      router.push('/login')
    }
  }
  return res.data
})

/**
 *
 * @param {} options 请求配置
 */
function request(options) {
  options.method = options.method || 'get'

  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  return service(options)
}

;['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
  request[item] = options => {
    return request({
      method: item,
      ...options
    })
  }
})

export default request
